﻿using KS3;
using RightControl.Common;
using RightControl.IService;
using RightControl.Model;
using System;
using System.Web.Mvc;

namespace RightControl.WebApp.Areas.Admin.Controllers {
    public class LoginController : Controller {
        private IUserService userService;
        private ILogService logService;
        public LoginController(IUserService _userService, ILogService _logService) {
            userService = _userService;
            logService = _logService;
        }
        // GET: Admin/Login
        public ActionResult Index() {
            ViewBag.Title = Configs.GetValue("SiteName");
            ViewBag.CopyRight = Configs.GetValue("CopyRight");
            ViewBag.SiteDomain = Configs.GetValue("SiteDomain");
            return View();
        }
        [HttpGet]
        public ActionResult GetAuthCode() {
            return File(VerifyCode.GetVerifyCode(VerifyCodeEnum.LogIn.ToString()), @"image/Gif");
        }

        [HttpGet]
        public ActionResult GetRegCode() {
            return File(VerifyCode.GetVerifyCode(VerifyCodeEnum.Register.ToString()), @"image/Gif");
        }

        [HttpPost]
        public ActionResult SendSMSCode(string mobileNo,string verifyCode) {
            if (string.IsNullOrEmpty(mobileNo) || string.IsNullOrEmpty(verifyCode)) {
                throw new Exception("信息有误，请确认后重试!");
            }
            //手机账号是否正确
            if (!HtmlUtils.IsTelephone(mobileNo)) {
                throw new Exception("请输入正确的手机号!");
            }     
            string codeSession = WebHelper.GetSession(VerifyCodeEnum.Register.ToString());
            WebHelper.RemoveSession(VerifyCodeEnum.Register.ToString());
            if (string.IsNullOrEmpty(codeSession) || Md5.md5(verifyCode.ToLower(), 16) != codeSession) {
                throw new Exception("验证码错误，请确认后重试!");
            }

            //手机账号是否重复           
            if (!userService.IsNotExist(new UserModel() { UserName = mobileNo })) {
                throw new Exception("该手机号已注册，请确认后重试!");
            }

            string rndYzm = RightControl.Common.Common.RandomCode();
            WebHelper.WriteSession(Constant.SmsYzmKey, rndYzm);

            string msg = "短信发送失败";
            return Content(new AjaxResult { state = ResultType.success.ToString(), message = msg }.ToJson());
        }

        [HttpGet]
        public ActionResult OutLogin() {
            if (OperatorProvider.Provider.GetCurrent() != null) {
                logService.WriteDbLog(new LogModel {
                    LogType = DbLogType.Exit.ToString(),
                    UserName = OperatorProvider.Provider.GetCurrent().UserName,
                    RealName = OperatorProvider.Provider.GetCurrent().RealName,
                    Status = true,
                    Description = "安全退出系统",
                });
            }

            Session.Abandon();
            Session.Clear();
            OperatorProvider.Provider.RemoveCurrent();
            return RedirectToAction("Index", "Login");
        }
         
        [HttpPost]
        public ActionResult CheckLogin(string username, string password, string code) {
            LogModel logEntity = new LogModel();
            logEntity.ModuleName = "系统登录";
            logEntity.LogType = DbLogType.Login.ToString();
            try {
                string codeSession = WebHelper.GetSession(VerifyCodeEnum.LogIn.ToString());
                WebHelper.RemoveSession(VerifyCodeEnum.LogIn.ToString());
                if (username.IsEmpty() || password.IsEmpty()) {
                      throw new Exception("用户名密码不能为空!");
                }
                if (string.IsNullOrEmpty(codeSession) || Md5.md5(code.ToLower(), 16) != codeSession) {
                    throw new Exception("验证码错误，请重新输入");
                }
                UserModel userEntity = userService.CheckLogin(username, password);
                if (userEntity != null) {
                    if (userEntity.ExpireTime < DateTime.Now) {
                        return Content(new AjaxResult { state = ResultType.error.ToString(), message = "账号已过期，请联系管理员。" }.ToJson());
                    }
                    OperatorModel operatorModel = new OperatorModel();
                    operatorModel.UserId = userEntity.Id;
                    operatorModel.UserName = userEntity.UserName;
                    operatorModel.RealName = userEntity.RealName;
                    operatorModel.RoleId = userEntity.RoleId;
                    operatorModel.HeadShot = userEntity.HeadShot;
                    operatorModel.LoginIPAddress = Net.Ip;
                    operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress);
                    operatorModel.LoginTime = DateTime.Now;
                    operatorModel.LoginToken = DESEncrypt.Encrypt(Guid.NewGuid().ToString());
                    operatorModel.IsSystem = userEntity.UserName == "admin";
                    OperatorProvider.Provider.AddCurrent(operatorModel);
                    logEntity.UserName = userEntity.UserName;
                    logEntity.RealName = userEntity.RealName;
                    logEntity.Status = true;
                    logEntity.Description = "登录成功";
                    logEntity.CreateBy = userEntity.Id;
                    logService.WriteDbLog(logEntity);

                    userEntity.LastLoginTime = DateTime.Now;
                    userService.UpdateModel(userEntity);
                    return Content(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功。" }.ToJson());
                }
                else {
                    throw new Exception("用户名或密码错误。");
                }
            }
            catch (Exception ex) {
                logEntity.UserName = username;
                logEntity.RealName = username;
                logEntity.Status = false;
                logEntity.Description = "登录失败，" + ex.Message;
                logService.WriteDbLog(logEntity);
                return Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson());
            }
        }

        [HttpPost]
        public ActionResult Register(string telNo, string password, string nickNm, string smsCode, int? refUser) {
            if (string.IsNullOrEmpty(telNo) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(nickNm) || string.IsNullOrEmpty(smsCode)) {
                throw new Exception("请将注册信息填写完整!");
            }
   
            string codeSession = WebHelper.GetSession(Constant.SmsYzmKey);
            WebHelper.RemoveSession(Constant.SmsYzmKey);
            if (string.IsNullOrEmpty(codeSession) || smsCode.ToLower() != codeSession) {
                throw new Exception("验证码错误，请确认后重试!");
            }
            //手机账号是否正确
            if (!HtmlUtils.IsTelephone(telNo)) {
                 throw new Exception("请输入正确的手机号!");
            }        

            UserModel user = new UserModel();
            user.UserName = telNo;
            user.PassWord = password;
            user.RealName = nickNm;
            user.RoleId = 3;
            user.RefUserId = refUser;
            user.ExpireTime = DateTime.Now.AddDays(3);
            user.CreateOn = DateTime.Now;

            //手机账号是否重复           
            if (!userService.IsNotExist(user)) {
                throw new Exception("该手机号已注册，请确认后重试!");
            }

            if (userService.CreateModel(user)) {
                return Content(new AjaxResult { state = ResultType.success.ToString(), message = "注册成功！" }.ToJson());
            }
            else {
                return Content(new AjaxResult { state = ResultType.error.ToString(), message = "注册失败，请稍后再试！" }.ToJson());
            }
        }
    }
}